2.3. Writing to the document
The document.write
function allows us to dynamically write HTML code to a document while
it is rendering. This was a very common technique in the ’90s, but
there are a lot of reasons for not using it in modern websites. Today,
the preferred technique is to manipulate the document using DOM after
the onload event.
Note:
If your script doesn’t use document.write, you should use the script
attribute defer="defer". This
will tell compatible browsers that they shouldn’t wait for the
script to download and/or execute to continue rendering the
document.
That said, in the mobile space sometimes it is better not to
deal with DOM (especially in low-end devices), so performing document.write operations can avoid a lot of
problems. As Table 5
shows, this technique still works on a lot of browsers.
Table 5. document.write compatibility table
Browser/platform | document.write
support |
---|
Safari | Yes |
Android
browser | Yes |
Symbian/S60 | Yes |
Nokia Series
40 | Before
6th edition, no after onload support |
webOS | Yes |
BlackBerry | Before 4.6, no after
onload
support |
NetFront | Yes |
Internet
Explorer | Yes |
Motorola Internet
Browser | Yes, no after onload support |
Opera
Mobile | Yes |
Opera
Mini | Server
rendering |
For example, you can create a year selection list dynamically to
save bytes in the original document. For rendering performance
purposes, it is better to use document.write with all the HTML at the same
time (including the beginning, contents, and end of a tag) rather than
partially writing a tag with many lines. The following code
demonstrates this technique:
<!DOCTYPE html PUBLIC "-//WAPFORUM//DTD XHTML Mobile 1.0//EN"
"http://www.wapforum.org/DTD/xhtml-mobile10.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Document Write</title>
<script type="text/javascript">
function createNumericSelect(name, from, to) {
var html = "<select name='" + name + "'>";
for (var i=from; i<to; i++) {
html += "<option>" + i + "</option>";
}
html += "</select>";
document.write(html);
}
</script>
</head>
<body>
<form action="send">
<script type="text/javascript">
createNumericSelect('year', 1990, 2020);
</script>
</form>
</body>
</html>
Remember that document.write
should not be used in an event handler, like onload or onclick, because it will have unpleasant
results. If you need to dynamically generate content on the page, it
is better to use DOM than document.write.